package org.example.Servlet;

import org.example.Dao.DamDao;
import org.example.Entity.Dam;
import org.example.Utils.DBUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONObject;

@WebServlet("/DoUpdateDamServlet")
public class DoUpdateDamServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String river = request.getParameter("river");
        double capacity = Double.parseDouble(request.getParameter("capacity"));
        String completeDate = request.getParameter("completeDate");

        Dam dam = new Dam();
        dam.setId(id);
        dam.setName(name);
        dam.setRiver(river);
        dam.setCapacity(capacity);
        dam.setCompleteDate(completeDate);

        Connection conn = null;
        try {
            conn = DBUtil.getConnection();
            DamDao damDao = new DamDao(conn);
            boolean success = damDao.updateDam(dam);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", success);
            response.setContentType("application/json");
            response.getWriter().write(jsonObject.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(500, "Internal Server Error");
        } finally {
            DBUtil.closeConnection(conn);
        }
    }
}